<template>
  <div class="container">
    <el-card>
      <div class="set-container">
        <div class="select-container">
          <el-form ref="selectForm" :inline="true" :model="selectForm" class="select-form">
            <el-form-item prop="username" label="用户名:">
              <el-input v-model="selectForm.username" placeholder="请输入要查找操作者的用户名"></el-input>
            </el-form-item>
            <el-form-item prop="date" label="操作时间:">
              <el-date-picker
                  v-model="selectForm.date"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item prop="sort" label="日志类别">
              <el-select class="select-input-2" v-model="selectForm.sort" placeholder="请选择" style="width: 100px">
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitSelect(1)">查询</el-button>
              <el-button type="info" @click="resetSelect">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="button-container">
          <el-button type="danger" @click="deleteDialog = true">批量删除</el-button>
          <el-button type="info">导出表格</el-button>
        </div>
      </div>
      <el-divider><h3 style="text-align: center">员工管理操作日志表格</h3></el-divider>
      <div class="table-container">
        <el-table
            v-if="tableData.length > 0"
            :data="tableData"
            @selection-change="handleSelectionChange"
            stripe
            border
            style="width: 100%">

          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="操作者用户名:">
                  <span>{{ props.row.username }}</span>
                </el-form-item>
                <el-form-item label="描述:">
                  <span>{{ props.row.description }}</span>
                </el-form-item>
                <el-form-item label="操作时间:">
                  <span>{{ props.row.time }}</span>
                </el-form-item>
                <el-form-item label="具体参数:">
                  <span>{{ props.row.methodParams }}</span>
                </el-form-item>
                <el-form-item label="操作类名:">
                  <span>{{ props.row.className }}</span>
                </el-form-item>
                <el-form-item label="操作方法名:">
                  <span>{{ props.row.methodName }}</span>
                </el-form-item>
                <el-form-item label="返回值:">
                  <span>{{ props.row.returnValue }}</span>
                </el-form-item>
                <el-form-item label="用时(ms):">
                  <span>{{ props.row.costTime }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>

          <el-table-column
              type="selection"
              width="50">
          </el-table-column>
          <el-table-column
              prop="username"
              label="操作者用户名"
              width="180">
          </el-table-column>
          <el-table-column
              prop="description"
              label="描述"
              width="200">
          </el-table-column>
          <el-table-column
              prop="time"
              label="操作时间"
              width="180">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              {{ formatCreateTime(scope.row.time) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="methodParams"
            label="具体参数"
            >
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>具体参数: {{ scope.row.methodParams }}</p>
                <div slot="reference" class="name-wrapper">
                 {{ scope.row.methodParams }}
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="costTime" label="用时（ms）" width=100>
          </el-table-column>
          <el-table-column prop="sort" label="类别" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.sort === 0" effect="dark">其它日志</el-tag>
              <el-tag v-else-if="scope.row.sort === 1" color="#0044FF" effect="dark">员工日志</el-tag>
              <el-tag v-else-if="scope.row.sort === 2" type="warning" effect="dark">用户日志</el-tag>
              <el-tag v-else-if="scope.row.sort === 3" type="info" effect="dark">商品日志</el-tag>
              <el-tag v-else-if="scope.row.sort === 4" type="success" effect="dark">分类日志</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="100">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty :image-size=350 v-else description="暂无数据"></el-empty>
      </div>
      <el-divider></el-divider>
        <div class="page">
          <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="selectForm.page"
              :page-sizes="[5, 7, 10, 20, 50]"
              :page-size="selectForm.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
      </div>
    </el-card>

    <el-dialog
        title="提示"
        :visible.sync="deleteDialog"
        width="30%">
      <h3 style="text-align: center;color: red">确认删除这些日志，删除后将无法恢复！</h3>
      <span slot="footer" class="dialog-footer">
    <el-button @click="deleteDialog = false">取 消</el-button>
    <el-button type="primary" @click="deleteByIds">确 定</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
import axios from "@/api/axios";

export default {
  data() {
    return {
      selectForm:{
        username:"",
        date:"",
        sort:"",
        pageSize:7,
        page:1
      },

      total:0,

      tableData:[],

      ids:[],

      deleteDialog:false,

      options: [
        {
          value: 0,
          label: '其它日志'
        }, {
          value: 1,
          label: '员工日志'
        }
        , {
          value: 2,
          label: '用户日志'
        }
        , {
          value: 3,
          label: '商品日志'
        }
        , {
          value: 4,
          label: '分类日志'
        }
      ],
    }
  },

  mounted() {
    this.submitSelect();
  },

  methods: {
    /**
     * 表格数据查询函数
     */
    submitSelect(flag) {
      this.$refs.selectForm.validate((valid) => {
        if (flag===1) {
          this.selectForm.page = 1;// 重新查询时，将页码置为第一页
        }

        if (valid) {
          const formData = {
            page: this.selectForm.page,
            pageSize: this.selectForm.pageSize,
            username: this.selectForm.username,
            sort: this.selectForm.sort,
            begin: this.formatDate(this.selectForm.date[0]),
            end: this.formatDate(this.selectForm.date[1]),
          };

          axios.post("/admin/log/list", formData).then(response => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            }else {
              this.tableData = response.data.data.records;
              this.total = response.data.data.total;
            }
          }).catch(error=> {
            // 处理请求错误
            console.log(error);
          });
        }else{
          console.log("error submit!");
          return false;
        }
      })
    },

    /**
     * 日期处理函数
     * @param date
     * @returns {null|string}
     */
    formatDate(date) {
      if (date instanceof Date) {
        // 返回格式化后的日期时间字符串（ISO 8601 UTC格式，不包含毫秒）
        return (
            date.toISOString().split("T")[0] +
            "T" +
            date.toISOString().split("T")[1].split(".")[0]
        );
      } else {
        // 如果日期为空或者不是Date对象，返回null或空字符串，或者根据你的需求返回其他默认值
        return null; // 或者 ""，取决于后端如何处理这种情况
      }
    },

    /**
     * 选择框
     */
    handleSelectionChange(val){
      // 创建一个新的数组来存储 id
      const ids = [];

      // 遍历 val 数组,并将每个对象的 id 属性值添加到 ids 数组中
      val.forEach(item => {
        ids.push(item.id);
      });

      this.ids = ids;
    },

    /**
     * 查询表单重置函数
     */
    resetSelect() {
      this.$refs.selectForm.resetFields(this.selectForm);
      this.$message.info("重置成功");
    },

    /**
     * 两个分页选项函数
     * @param val
     */
    handleSizeChange(val) {
      this.selectForm.pageSize = val;
      this.submitSelect();
    },
    handleCurrentChange(val) {
      this.selectForm.page=val;
      this.submitSelect();
    },

    /**
     * 给返回的时间格式化函数
     * @param {Array} createTime - 包含年、月、日、时、分、秒的数组
     * @returns {string}
     */
    formatCreateTime(createTime) {
      const [year, month, day, hour, minute = '00', second = '00'] = createTime;
      return `${year}-${this.padZero(month)}-${this.padZero(day)} ${this.padZero(hour)}:${this.padZero(minute)}:${this.padZero(second)}`;
    },

    /**
     * 将数字补零
     * @param {number|string} num
     * @returns {string}
     */
    padZero(num) {
      return num.toString().padStart(2, '0');
    },

    /**
     * 删除
     */
    handleDelete(id) {
      const ids = [id]; // 将 id 放到一个数组中
      axios.delete("/admin/log/delete", {
        data: ids // 将 ids 数组作为请求体发送
      })
          .then(response => {
            if (response.data.code === 0) {
              this.$message.error(response.data.msg);
            } else {
              this.$message.success("删除成功");
             this.submitSelect();
            }
          })
          .catch(error => {
            console.log(error);
          });
    },

    /**
     * 批量删除
     */
    deleteByIds(){
      this.deleteDialog=false;
      if(this.ids.length===0){
        this.$message.error("未选择要删除的日志");
        return;
      }
      axios.delete("/admin/log/delete", {
        data:this.ids
      }).then(response => {
        if (response.data.code === 0) {
          this.$message.error(response.data.msg);
        }else {
          this.$message.success("删除成功");
         this.submitSelect();
        }
      }).catch(error => {
        console.log(error);
      })
    }
  }
}
</script>

<style scoped>
/*表格顶部设置栏*/
.set-container{
  display: flex;
}

.button-container{
  margin-left: auto; /* 将按钮容器向右对齐 */
}

/*表格最小高度*/
.table-container{
  min-height: 60vh;
}

/*分页*/
.page{
  margin-top: 20px;
}

/*单元行详情*/
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>